package com.example.demo.web.services;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.async.DeferredResult;

import com.example.demo.web.Entity.LockMissionDetailEntity;
import com.example.demo.web.Entity.LockUserEntity;
import com.example.demo.web.Entity.MissionDetailEntity;
import com.example.demo.web.Entity.MissionEntity;
import com.example.demo.web.Entity.OrganizationEntity;
import com.example.demo.web.Entity.UserEntity;
import com.example.demo.web.Entity.UserLogEntity;
import com.example.demo.web.dao.LockDAO;
import com.example.demo.web.dao.MissionDAO;
import com.example.demo.web.dao.UserDAO;
import com.example.demo.web.util.XinLongUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Service
@Transactional
public class MissionService {
	private Logger log = LogManager.getLogger(MissionService.class);
	private MissionDAO missionDao;
	@Autowired
	public void setMissionDAO(MissionDAO missionDao) {
		this.missionDao = missionDao;
	}  
	
	private UserDAO userDao;
    @Autowired
    public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}
    
    private LockDAO lockDao;
    @Autowired
    public void setLockDao(LockDAO lockDao) {
		this.lockDao = lockDao;
	}

	public void _getMissionlist(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	int pageNumber = 0;
		int pageSize = 0;
		String owner = "";
		String orgname = "";
		String locksn = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			pageNumber =rootNode.get("pageNumber").asInt();
			pageSize =rootNode.get("pageSize").asInt();		
			owner =rootNode.get("owner").asText();
			orgname =rootNode.get("orgname").asText();
			locksn =rootNode.get("locksn").asText();
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
    	List<MissionEntity> mlist = null;
    	int precount = 0;
    	//判断用户角色,根据用户是否有创建任务权限判断是否为日常管理员
    	if(userDao.findRoleByUsername(sentity.getUsername()) < 3) {
    		//日常管理员
    		List<OrganizationEntity> suborgs = null;
    		if(userDao.isRootOrg(sentity.getOrg_id())) {
    			mlist =missionDao.findByQuery(owner,orgname,locksn,pageNumber, pageSize);
    			precount = missionDao.findByQueryCount(owner,orgname,locksn);
    		}else {
    			suborgs = missionDao.findSubOrg(sentity.getOrg_id());
    			if(suborgs != null && suborgs.size() > 0){
        			mlist =missionDao.findByQuery(suborgs,owner,orgname,locksn,pageNumber, pageSize);
        			precount = missionDao.findByQueryCount(suborgs,owner,orgname,locksn);
            	}
    		}

    	}else {
    		//柜员或主管,只显示自己的任务
    		mlist = missionDao.findMissionByAuther(sentity.getUsername(),pageNumber, pageSize);
    		precount = missionDao.findMissionByAutherCount(sentity.getUsername());
    	}
    	
    	
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	ArrayNode rootnode = mapper.createArrayNode();
    	if(mlist != null && mlist.size() > 0){
    		ObjectNode tjson = null;
    		for(MissionEntity mission : mlist){
    			tjson = mapper.createObjectNode();
    			tjson.put("id", mission.getId());
    			tjson.put("createname", mission.getCreatename());
    			tjson.put("createtime", sdf.format(mission.getCreatetime()));    			
    			tjson.put("mtype", mission.getMtype());
    			tjson.put("authuser", mission.getAuthuser());
    			tjson.put("auth_reals", mission.getAuth_reals());
    			tjson.put("locksn", mission.getLocksn());
    			tjson.put("stime", sdf.format(mission.getStime()));
    			tjson.put("etime", sdf.format(mission.getEtime()));
    			tjson.put("active", mission.getActive());
    			tjson.put("boxid", mission.getBoxid());
    			tjson.put("keyvalid", mission.getKeyvalid());
    			tjson.put("stopreason", mission.getStopreason());
    			tjson.put("orgname", mission.getOrgname());
    			tjson.put("orgid", mission.getOrgid());
    			tjson.put("descriptor", mission.getDescriptor());
    			rootnode.add(tjson);
        	}
    		
    	}
    	
    	resjson.put("status", "1");
    	resjson.put("totalCount", precount);
    	resjson.put("pageSize", pageSize);
    	if(sentity.getUsername().equals("hzwlprevail")){
			resjson.put("needcheck", 0);
		}else{
			resjson.put("needcheck", XinLongUtil.isNeedCheck("资产管理/任务管理/导出"));
		}
    	resjson.put("datalist", rootnode);
    	deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
	
	public void _getAllotMissionlist(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	int pageNumber = 0;
		int pageSize = 0;
		String boxid = "";
		String orgname = "";
		String locksn = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			pageNumber =rootNode.get("pageNumber").asInt();
			pageSize =rootNode.get("pageSize").asInt();		
			boxid =rootNode.get("boxid").asText();
			orgname =rootNode.get("orgname").asText();
			locksn =rootNode.get("locksn").asText();
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
    	List<MissionEntity> mlist = null;
    	int precount = 0;
    	//判断用户角色,根据用户是否有创建任务权限判断是否为日常管理员
    	int roleflag = userDao.findRoleByUsername(sentity.getUsername());
    	if(roleflag ==7 || roleflag == 1) {
    		//调拨管理员和系统管理员
    		List<OrganizationEntity> suborgs = null;
    		if(userDao.isRootOrg(sentity.getOrg_id())) {
    			mlist =missionDao.findAllotByQuery(boxid,orgname,locksn,pageNumber, pageSize);
    			precount = missionDao.findAllotByQueryCount(boxid,orgname,locksn);
    		}else {
    			suborgs = missionDao.findSubOrg(sentity.getOrg_id());
    			if(suborgs != null && suborgs.size() > 0){
        			mlist =missionDao.findAllotByQuery(suborgs,boxid,orgname,locksn,pageNumber, pageSize);
        			precount = missionDao.findAllotByQueryCount(suborgs,boxid,orgname,locksn);
            	}
    		}

    	}else {
    		//柜员或主管,只显示自己的任务
    		mlist = missionDao.findAllotMissionByAuther(sentity.getUsername(),pageNumber, pageSize);
    		precount = missionDao.findAllotMissionByAutherCount(sentity.getUsername());
    	}
    	
    	
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	ArrayNode rootnode = mapper.createArrayNode();
    	if(mlist != null && mlist.size() > 0){
    		ObjectNode tjson = null;
    		for(MissionEntity mission : mlist){
    			tjson = mapper.createObjectNode();
    			tjson.put("id", mission.getId());
    			tjson.put("createname", mission.getCreatename());
    			tjson.put("createtime", sdf.format(mission.getCreatetime()));    			
    			tjson.put("mtype", mission.getMtype());
    			tjson.put("authuser", mission.getAuthuser());
    			tjson.put("auth_reals", mission.getAuth_reals());
    			tjson.put("locksn", mission.getLocksn());
    			tjson.put("stime", sdf.format(mission.getStime()));
    			tjson.put("etime", sdf.format(mission.getEtime()));
    			tjson.put("active", mission.getActive());
    			tjson.put("boxid", mission.getBoxid());
    			tjson.put("keyvalid", mission.getKeyvalid());
    			tjson.put("stopreason", mission.getStopreason());
    			tjson.put("orgname", mission.getOrgname());
    			tjson.put("orgid", mission.getOrgid());
    			tjson.put("descriptor", mission.getDescriptor());
    			rootnode.add(tjson);
        	}
    		
    	}
    	
    	resjson.put("status", "1");
    	resjson.put("totalCount", precount);
    	resjson.put("pageSize", pageSize);
    	if(sentity.getUsername().equals("hzwlprevail")){
			resjson.put("needcheck", 0);
		}else{
			resjson.put("needcheck", XinLongUtil.isNeedCheck("资产管理/任务管理/导出"));
		}
    	resjson.put("datalist", rootnode);
    	deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
	
	public void _getMultiMissionlist(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	int pageNumber = 0;
		int pageSize = 0;
		String owner = "";
		String orgname = "";
		String locksn = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			pageNumber =rootNode.get("pageNumber").asInt();
			pageSize =rootNode.get("pageSize").asInt();		
			owner =rootNode.get("owner").asText();
			orgname =rootNode.get("orgname").asText();
			locksn =rootNode.get("locksn").asText();
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
    	List<MissionEntity> mlist = null;
    	int precount = 0;
    	//判断用户角色,根据用户是否有创建任务权限判断是否为日常管理员
    	if(userDao.findRoleByUsername(sentity.getUsername()) < 3) {
    		//日常管理员
    		List<OrganizationEntity> suborgs = missionDao.findSubOrg(sentity.getOrg_id());
        	
    		if(suborgs != null && suborgs.size() > 0){
    			mlist =missionDao.findMultiByQuery(suborgs,owner,orgname,locksn,pageNumber, pageSize);
    			precount = missionDao.findMultiByQueryCount(suborgs,owner,orgname,locksn);
        	}
    	}else {
    		//柜员或主管,只显示自己的任务
    		mlist = missionDao.findMissionByAuther(sentity.getRealName(),pageNumber, pageSize);
    		precount = missionDao.findMissionByAutherCount(sentity.getUsername());
    	}
    	
    	
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	ArrayNode rootnode = mapper.createArrayNode();
    	if(mlist != null && mlist.size() > 0){
    		ObjectNode tjson = null;
    		for(MissionEntity mission : mlist){
    			tjson = mapper.createObjectNode();
    			tjson.put("id", mission.getId());
    			tjson.put("createname", mission.getCreatename());
    			tjson.put("createtime", sdf.format(mission.getCreatetime()));    			
    			tjson.put("mtype", mission.getMtype());
    			tjson.put("authuser", mission.getAuthuser());
    			tjson.put("auth_reals", mission.getAuth_reals());
    			tjson.put("locksn", mission.getLocksn());
    			tjson.put("stime", sdf.format(mission.getStime()));
    			tjson.put("etime", sdf.format(mission.getEtime()));
    			tjson.put("active", mission.getActive());
    			tjson.put("stopreason", mission.getStopreason());
    			tjson.put("orgname", mission.getOrgname());
    			tjson.put("orgid", mission.getOrgid());
    			tjson.put("descriptor", mission.getDescriptor());
    			rootnode.add(tjson);
        	}
    		
    	}
    	
    	resjson.put("status", "1");
    	resjson.put("totalCount", precount);
    	resjson.put("pageSize", pageSize);
    	if(sentity.getUsername().equals("hzwlprevail")){
			resjson.put("needcheck", 0);
		}else{
			resjson.put("needcheck", XinLongUtil.isNeedCheck("资产管理/任务管理/导出"));
		}
    	resjson.put("datalist", rootnode);
    	deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
    
    public void _missionadd(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
		String descriptor = "";
		String stime = "";
		String etime = "";
		int mtype = 0;
		int keyvalid = 0;
		String ckname = "";
		String orgid = "";
		JsonNode authuser = null;
		JsonNode childrenNode = null;
		LockMissionDetailEntity detail = null;
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			stime =rootNode.get("stime").asText();
			etime =rootNode.get("etime").asText();
			descriptor =rootNode.get("descriptor").asText();
			mtype =rootNode.get("mtype").asInt();
			keyvalid =rootNode.get("keyvalid").asInt();
			ckname =rootNode.get("ckname").asText();
			orgid =rootNode.get("orgid").asText();
			childrenNode = rootNode.path("locks"); 
			authuser = rootNode.path("authuser"); 
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date start = null;
		Date end = null;
		
    	try {
    		start = dateFormat.parse(stime);
    		end = dateFormat.parse(etime);
    		if(end.before(start)) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于生效时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    		if(end.before(new Date())) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于当前时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    	}catch(Exception e) {
    		resjson.put("status", "2");
			resjson.put("desc", "任务时间设置异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	
    	Date date = new Date();
    	MissionEntity mission = new MissionEntity();
    	mission.setId(UUID.randomUUID().toString().replace("-", ""));
    	mission.setCreatename(sentity.getUsername());
    	mission.setCreatetime(date);
    	StringBuilder authlist = new StringBuilder();
    	StringBuilder sb = new StringBuilder();
		Iterator<JsonNode> authit = authuser.iterator();
		int i = 0;
		while(authit.hasNext()){
    		JsonNode jnode = authit.next();
    		if(i == 0) {
    			authlist.append(jnode.get("username").asText());
    			sb.append(jnode.get("oper_reals").asText());
    		}else {
    			authlist.append("," + jnode.get("username").asText());
    			sb.append("," + jnode.get("oper_reals").asText());
    		}
    		i++;
		}
		mission.setAuthuser(authlist.toString());
    	mission.setAuth_reals(sb.toString());
    	mission.setStime(start);
    	mission.setEtime(end);
    	mission.setDescriptor(descriptor);
    	mission.setOrgid(orgid);
    	mission.setMtype(mtype);
    	mission.setCkname(ckname);
    	mission.setKeyvalid(keyvalid);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/任务管理/创建任务");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_missionadd");
		ulog.setOrgid(sentity.getOrg_id());
		
		//添加锁具授权信息
		if(mtype == 1) {
			//批量任务
			Iterator<JsonNode> it = authuser.iterator();
			String username = "";
			
			List<LockUserEntity> lockuserlist = null;
    		while(it.hasNext()){
	    		JsonNode jnode = it.next();
	    		username = jnode.get("username").asText();
	    		lockuserlist = lockDao.findUserLocksByUser(username);
	    		for(LockUserEntity lockuser : lockuserlist) {
	    			if(lockuser.getLocktype() == 3) {
	    				//调拨锁，这里不做处理
	    				continue;
	    			}
	    			//判断是否是同一任务授权
	    			if(!lockuser.getMissionid().equals(mission.getId()) && !lockuser.getMissionid().equals("")) {
	    				if(lockuser.getActive() == 1) {
	    					mission = missionDao.findMissionById(lockuser.getMissionid());
		    				resjson.put("status", "2");
		    				resjson.put("desc", "锁具["+ lockuser.getLocksn() + "]已在任务时间段[" + mission.getStime() + "-" + mission.getEtime() + "]授权!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;	
	    				}else {
	    					lockuser.setActive(1);
	    					lockuser.setMissionid(mission.getId());
	    					if(lockDao.updatelockuserActive(lockuser) == 0) {
	    						resjson.put("status", "2");
			    				resjson.put("desc", "更新锁具["+ lockuser.getLocksn() + "]授权信息失败!");
			    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			    				deferredResult.setResult(mapper.writeValueAsString(resjson));
			    				return;
	    					}
	    				}
	    			}else {
	    				if(lockuser.getActive() == 1) {
	    					continue;
	    				}else {
	    					lockuser.setActive(1);
	    					lockuser.setMissionid(mission.getId());
	    					if(lockDao.updatelockuserActive(lockuser) == 0) {
	    						resjson.put("status", "2");
			    				resjson.put("desc", "更新锁具["+ lockuser.getLocksn() + "]授权信息失败!");
			    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			    				deferredResult.setResult(mapper.writeValueAsString(resjson));
			    				return;
	    					}
	    					
	    				}
	    			}
	    			//添加任务详情列表
					detail = new LockMissionDetailEntity();
					detail.setId(UUID.randomUUID().toString().replace("-", ""));
					detail.setStime(mission.getStime());
					detail.setEtime(mission.getEtime());
					detail.setAuthuser(lockuser.getOperators());
					detail.setAuth_reals(lockuser.getOper_reals());
					detail.setLocksn(lockuser.getLocksn());
					detail.setMissionid(mission.getId());
					detail.setActive(1);
					if(missionDao.insertLockMissionDetail(detail) == 0) {
						resjson.put("status", "2");
	    				resjson.put("desc", "添加锁具["+ lockuser.getLocksn() + "]任务信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
					}
	    		}   		
	    		
    		}
		}else if(mtype == 0) {
			//应急任务
			Iterator<JsonNode> it = childrenNode.iterator();
			LockUserEntity lockuser = null;
	    	while(it.hasNext()){
	    		JsonNode jnode = it.next();
	    		lockuser = lockDao.findLockUserByLock(jnode.get("locksn").asText());
	    		if(lockuser != null) {
	    			mission.setLocksn(lockuser.getLocksn());
	    			if(lockuser.getActive() == 1 && !lockuser.getMissionid().equals("") && !lockuser.getMissionid().equalsIgnoreCase(mission.getId()) ) {
	    				mission = missionDao.findMissionById(lockuser.getMissionid());
	    				resjson.put("status", "2");
	    				resjson.put("desc", "锁具[" + lockuser.getLocksn() + "]已在任务时间段[" + mission.getStime() + "-" + mission.getEtime() + "]授权!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
	    			}
	    			if(lockuser.getOpentype() == 0) {
	    				if(authlist.toString().indexOf(",") >= 0) {
	    					resjson.put("status", "2");
		    				resjson.put("desc", "开锁模式为单人,无法授权两人!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;
	    				}
	    			}else {
	    				if(authlist.toString().indexOf(",") < 0) {
	    					resjson.put("status", "2");
		    				resjson.put("desc", "开锁模式为双人,请选择两人授权!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;
	    				}
	    			}
	    			lockuser.setActive(1);
	    			lockuser.setMissionid(mission.getId());
	    			if(lockDao.updatelockuserActive(lockuser) == 0) {
	    				resjson.put("status", "2");
	    				resjson.put("desc", "更新授权信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
	    			}
	    			//添加任务详情列表
					detail = new LockMissionDetailEntity();
					detail.setId(UUID.randomUUID().toString().replace("-", ""));
					detail.setStime(mission.getStime());
					detail.setEtime(mission.getEtime());
					detail.setAuthuser(authlist.toString());
					detail.setAuth_reals(sb.toString());
					detail.setLocksn(lockuser.getLocksn());
					detail.setMissionid(mission.getId());
					detail.setActive(1);
					if(missionDao.insertLockMissionDetail(detail) == 0) {
						resjson.put("status", "2");
	    				resjson.put("desc", "添加锁具["+ lockuser.getLocksn() + "]任务信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
					}
	    		}else {
	    			resjson.put("status", "2");
    				resjson.put("desc", "找不到锁具[" + jnode.get("locksn").asText() + "]使用人信息!");
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    				deferredResult.setResult(mapper.writeValueAsString(resjson));
    				return;
	    		}
	    	}
		}else if(mtype == 2) {
			//金库任务
			Iterator<JsonNode> it = authuser.iterator();
			String roleid = "";
			//金库任务需金库主管一名，金库经办一名
			boolean hasZ = false;
			boolean hasJ = false;
    		while(it.hasNext()){
	    		JsonNode jnode = it.next();
	    		roleid = jnode.get("roleid").asText();
	    		if(roleid.equals("49c75a023afd4e608ab0bf82f3441dcd")) {
	    			hasJ = true;
	    			//判断人员是否有已生效的金库任务
	    			if(missionDao.findActiveJinkuMissionByAuther(jnode.get("username").asText()) != null) {
	    				resjson.put("status", "2");
	        			resjson.put("desc", jnode.get("oper_reals").asText() + "已有正在执行的金库任务!");
	        			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	        			deferredResult.setResult(mapper.writeValueAsString(resjson));
	        			return;
	    			}
	    		}else if(roleid.equals("727a4c59b9054e8e9324b201bb19c1a6")) {
	    			hasZ = true;
	    			if(missionDao.findActiveJinkuMissionByAuther(jnode.get("username").asText()) != null) {
	    				resjson.put("status", "2");
	        			resjson.put("desc", jnode.get("oper_reals").asText() + "已有正在执行的金库任务!");
	        			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	        			deferredResult.setResult(mapper.writeValueAsString(resjson));
	        			return;
	    			}
	    		}
    		}
    		if(hasJ && hasZ) {
    			
    		}else {
    			resjson.put("status", "2");
    			resjson.put("desc", "金库任务需金库主管一名，金库经办一名!");
    			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
		}
		else {
			resjson.put("status", "2");
			resjson.put("desc", "未知任务类型失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		
		
		if(missionDao.savemission(mission) == 0) {
			resjson.put("status", "2");
			resjson.put("desc", "创建任务失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		resjson.put("status", "1");
		resjson.put("desc", "创建成功!");
		if(mtype == 0) {
			ulog.setDescriptor("创建日常任务");
		}else {
			ulog.setDescriptor("创建应急任务");
		}			
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
    
    public void _missionstop(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
		String missionid = "";
		String stopreason = "";
		String ckname = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			missionid =rootNode.get("missionid").asText();
			stopreason =rootNode.get("descriptor").asText();
			ckname =rootNode.get("ckname").asText();
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		
    	Date date = new Date();
    	if(missionDao.stopmission(missionid,stopreason) == -1) {
    		resjson.put("status", "2");
			resjson.put("desc", "更新任务异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	//更新锁具授权信息
    	MissionEntity mission = missionDao.findMissionById(missionid);
    	if(mission == null) {
    		resjson.put("status", "2");
			resjson.put("desc", "找不到指定任务!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	};
    	if(lockDao.ResetLockUserInfoByMission(missionid) == -1) {
			resjson.put("status", "2");
			resjson.put("desc", "更新任务授权信息失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
    	if(missionDao.updateLockMissionDetail_reasonByid(missionid, stopreason) == -1) {
			log.error("手动终止任务时更新终止原因失败!");
		}
    	SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/任务管理/终止任务");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_missionstop");
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setDescriptor("终止日常任务");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		resjson.put("status", "1");
		resjson.put("desc", "操作成功!");
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}   
    
    public void _missionedit(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
		String missionid = "";
		String descriptor = "";
		String stime = "";
		String etime = "";
		String ckname = "";
		int mtype = 0;
		int keyvalid = 0;
		JsonNode authuser = null;
		JsonNode childrenNode = null;
		LockMissionDetailEntity detail = null;
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			missionid =rootNode.get("missionid").asText();
			stime =rootNode.get("stime").asText();
			etime =rootNode.get("etime").asText();
			descriptor =rootNode.get("descriptor").asText();
			ckname =rootNode.get("ckname").asText();
			mtype =rootNode.get("mtype").asInt();
			keyvalid =rootNode.get("keyvalid").asInt();
			childrenNode = rootNode.path("locks"); 
			authuser = rootNode.path("authuser"); 
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date start = null;
		Date end = null;
		
    	try {
    		start = dateFormat.parse(stime);
    		end = dateFormat.parse(etime);
    		if(end.before(start)) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于生效时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    		if(end.before(new Date())) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于当前时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    	}catch(Exception e) {
    		resjson.put("status", "2");
			resjson.put("desc", "任务时间设置异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	
    	Date date = new Date();
    	MissionEntity mission = missionDao.findMissionById(missionid);
    	if(mission == null) {
    		resjson.put("status", "2");
			resjson.put("desc", "找不到指定任务!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	};
    	StringBuilder authlist = new StringBuilder();
    	StringBuilder sb = new StringBuilder();
		Iterator<JsonNode> authit = authuser.iterator();
		int i = 0;
		while(authit.hasNext()){
    		JsonNode jnode = authit.next();
    		if(i == 0) {
    			authlist.append(jnode.get("username").asText());
    			sb.append(jnode.get("oper_reals").asText());
    		}else {
    			authlist.append("," + jnode.get("username").asText());
    			sb.append("," + jnode.get("oper_reals").asText());
    		}
    		i++;
		}
    	mission.setStime(start);
    	mission.setEtime(end);
    	mission.setDescriptor(descriptor);
    	mission.setCkname(ckname);
    	mission.setStopreason("");
    	mission.setAuthuser(authlist.toString());
    	mission.setAuth_reals(sb.toString());
    	mission.setActive(0);
    	mission.setKeyvalid(keyvalid);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/任务管理/编辑任务");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_missionedit");
		ulog.setOrgid(sentity.getOrg_id());
		
		//清空任务id下的授权信息
		if(lockDao.ResetLockUserInfoByMission(mission.getId()) == 0) {
			resjson.put("status", "2");
			resjson.put("desc", "重置任务授权信息失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		//删除原任务id对应的详情列表
		if(missionDao.deleteLockMissionDetail(mission.getId()) == -1) {
			resjson.put("status", "2");
			resjson.put("desc", "重置任务列表信息失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		//修改锁具授权信息
		if(mtype == 1) {
			//批量任务
			Iterator<JsonNode> it = authuser.iterator();
			String username = "";

			List<LockUserEntity> lockuserlist = null;
    		while(it.hasNext()){
	    		JsonNode jnode = it.next();
	    		username = jnode.get("username").asText();
	    		lockuserlist = lockDao.findUserLocksByUser(username);
	    		for(LockUserEntity lockuser : lockuserlist) {
	    			if(lockuser.getLocktype() == 3) {
	    				//调拨锁，这里不做处理
	    				continue;
	    			}
	    			//判断是否是同一任务授权
	    			if(!lockuser.getMissionid().equals(mission.getId()) && !lockuser.getMissionid().equals("")) {
	    				if(lockuser.getActive() == 1) {
	    					mission = missionDao.findMissionById(lockuser.getMissionid());
		    				resjson.put("status", "2");
		    				resjson.put("desc", "锁具["+ lockuser.getLocksn() + "]已在任务时间段[" + mission.getStime() + "-" + mission.getEtime() + "]授权!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;	
	    				}else {
	    					lockuser.setActive(1);
	    					lockuser.setMissionid(mission.getId());
	    					if(lockDao.updatelockuserActive(lockuser) == 0) {
	    						resjson.put("status", "2");
			    				resjson.put("desc", "更新锁具["+ lockuser.getLocksn() + "]授权信息失败!");
			    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			    				deferredResult.setResult(mapper.writeValueAsString(resjson));
			    				return;
	    					}
	    				}
	    			}else {
	    				if(lockuser.getActive() == 1) {
	    					continue;
	    				}else {
	    					lockuser.setActive(1);
	    					if(lockDao.updatelockuserActive(lockuser) == 0) {
	    						resjson.put("status", "2");
			    				resjson.put("desc", "更新锁具["+ lockuser.getLocksn() + "]授权信息失败!");
			    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			    				deferredResult.setResult(mapper.writeValueAsString(resjson));
			    				return;
	    					}
	    				}
	    			}
	    			//添加任务详情列表
					detail = new LockMissionDetailEntity();
					detail.setId(UUID.randomUUID().toString().replace("-", ""));
					detail.setStime(mission.getStime());
					detail.setEtime(mission.getEtime());
					detail.setAuthuser(lockuser.getOperators());
					detail.setAuth_reals(lockuser.getOper_reals());
					detail.setLocksn(lockuser.getLocksn());
					detail.setMissionid(mission.getId());
					detail.setActive(1);
					if(missionDao.insertLockMissionDetail(detail) == 0) {
						resjson.put("status", "2");
	    				resjson.put("desc", "添加锁具["+ lockuser.getLocksn() + "]任务信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
					}
	    		}   		
	    		
    		}
		}else if(mtype == 0){
			//应急任务
			Iterator<JsonNode> it = childrenNode.iterator();
			LockUserEntity lockuser = null;
	    	while(it.hasNext()){
	    		JsonNode jnode = it.next();
	    		lockuser = lockDao.findLockUserByLock(jnode.get("locksn").asText());
	    		if(lockuser != null) {
	    			mission.setLocksn(lockuser.getLocksn());
	    			if(lockuser.getActive() == 1 && !lockuser.getMissionid().equals("") && !lockuser.getMissionid().equalsIgnoreCase(mission.getId()) ) {
	    				mission = missionDao.findMissionById(lockuser.getMissionid());
	    				resjson.put("status", "2");
	    				resjson.put("desc", "锁具[" + lockuser.getLocksn() + "]已在任务时间段[" + mission.getStime() + "-" + mission.getEtime() + "]授权!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
	    			}
	    			if(lockuser.getOpentype() == 0) {
	    				if(authlist.toString().indexOf(",") >= 0) {
	    					resjson.put("status", "2");
		    				resjson.put("desc", "开锁模式为单人,无法授权两人!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;
	    				}
	    			}else {
	    				if(authlist.toString().indexOf(",") < 0) {
	    					resjson.put("status", "2");
		    				resjson.put("desc", "开锁模式为双人,请选择两人授权!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;
	    				}
	    			}
	    			lockuser.setActive(1);
	    			lockuser.setMissionid(mission.getId());
	    			if(lockDao.updatelockuserActive(lockuser) == 0) {
	    				resjson.put("status", "2");
	    				resjson.put("desc", "更新授权信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
	    			}
	    			//添加任务详情列表
					detail = new LockMissionDetailEntity();
					detail.setId(UUID.randomUUID().toString().replace("-", ""));
					detail.setStime(mission.getStime());
					detail.setEtime(mission.getEtime());
					detail.setAuthuser(authlist.toString());
					detail.setAuth_reals(sb.toString());
					detail.setLocksn(lockuser.getLocksn());
					detail.setMissionid(mission.getId());
					detail.setActive(1);
					if(missionDao.insertLockMissionDetail(detail) == 0) {
						resjson.put("status", "2");
	    				resjson.put("desc", "添加锁具["+ lockuser.getLocksn() + "]任务信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
					}
	    		}else {
	    			resjson.put("status", "2");
    				resjson.put("desc", "找不到锁具[" + jnode.get("locksn").asText() + "]使用人信息!");
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    				deferredResult.setResult(mapper.writeValueAsString(resjson));
    				return;
	    		}
	    	}
		}else if(mtype == 2) {
			//金库任务
			Iterator<JsonNode> it = authuser.iterator();
			String username = "";
			int roleflag = 0;
			//金库任务需金库主管一名，金库经办一名
			boolean hasZ = false;
			boolean hasJ = false;
    		while(it.hasNext()){
	    		JsonNode jnode = it.next();
	    		username = jnode.get("username").asText();
	    		roleflag = userDao.findRoleByUsername(username);
	    		if(roleflag == 6) {
	    			hasJ = true;
	    		}else if(roleflag == 5) {
	    			hasZ = true;
	    		}
    		}
    		if(hasJ && hasZ) {
    			
    		}else {
    			resjson.put("status", "2");
    			resjson.put("desc", "金库任务需金库主管一名，金库经办一名!");
    			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
		}else {
			resjson.put("status", "2");
			resjson.put("desc", "未知任务类型失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		if(missionDao.updatemission(mission) == 0) {
			resjson.put("status", "2");
			resjson.put("desc", "编辑任务失败!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		resjson.put("status", "1");
		resjson.put("desc", "更新成功!");
		if(mtype == 0) {
			ulog.setDescriptor("更新日常任务");
		}else {
			ulog.setDescriptor("更新应急任务");
		}			
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
    
    public void _allotmissionadd(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
		String descriptor = "";
		String stime = "";
		String etime = "";
		int mtype = 0;
		int keyvalid = 0;
		String ckname = "";
		String orgid = "";
		JsonNode authuser = null;
		JsonNode childrenNode = null;
		LockMissionDetailEntity detail = null;
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			stime =rootNode.get("stime").asText();
			etime =rootNode.get("etime").asText();
			descriptor =rootNode.get("descriptor").asText();
			mtype =rootNode.get("mtype").asInt();
			keyvalid =rootNode.get("keyvalid").asInt();
			ckname =rootNode.get("ckname").asText();
			orgid =rootNode.get("orgid").asText();
			childrenNode = rootNode.path("locks"); 
			authuser = rootNode.path("authuser"); 
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date start = null;
		Date end = null;
		
    	try {
    		start = dateFormat.parse(stime);
    		end = dateFormat.parse(etime);
    		if(end.before(start)) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于生效时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    		if(end.before(new Date())) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于当前时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    	}catch(Exception e) {
    		resjson.put("status", "2");
			resjson.put("desc", "任务时间设置异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	
    	Date date = new Date();
    	MissionEntity mission = new MissionEntity();
    	mission.setId(UUID.randomUUID().toString().replace("-", ""));
    	mission.setCreatename(sentity.getUsername());
    	mission.setCreatetime(date);
    	StringBuilder authlist = new StringBuilder();
    	StringBuilder sb = new StringBuilder();
		Iterator<JsonNode> authit = authuser.iterator();
		int i = 0;
		while(authit.hasNext()){
    		JsonNode jnode = authit.next();
    		if(i == 0) {
    			authlist.append(jnode.get("username").asText());
    			sb.append(jnode.get("oper_reals").asText());
    		}else {
    			authlist.append("," + jnode.get("username").asText());
    			sb.append("," + jnode.get("oper_reals").asText());
    		}
    		i++;
		}
		mission.setAuthuser(authlist.toString());
    	mission.setAuth_reals(sb.toString());
    	mission.setStime(start);
    	mission.setEtime(end);
    	mission.setDescriptor(descriptor);
    	mission.setOrgid(orgid);
    	mission.setMtype(mtype);
    	mission.setCkname(ckname);
    	mission.setKeyvalid(keyvalid);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/调拨任务/创建任务");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_allotmissionadd");
		ulog.setOrgid(sentity.getOrg_id());
		
		//调拨任务
		Iterator<JsonNode> it = childrenNode.iterator();
		LockUserEntity lockuser = null;
    	while(it.hasNext()){
    		JsonNode jnode = it.next();
    		lockuser = lockDao.findLockUserByLock(jnode.get("locksn").asText());
    		if(lockuser != null) {
    			mission.setLocksn(lockuser.getLocksn());
    			mission.setBoxid(jnode.get("boxid").asText());
    			if(lockuser.getActive() == 1 && !lockuser.getMissionid().equals("") && !lockuser.getMissionid().equalsIgnoreCase(mission.getId()) ) {
    				mission = missionDao.findMissionById(lockuser.getMissionid());
    				resjson.put("status", "2");
    				resjson.put("desc", "锁具[" + lockuser.getLocksn() + "]已在任务时间段[" + mission.getStime() + "-" + mission.getEtime() + "]授权!");
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    				deferredResult.setResult(mapper.writeValueAsString(resjson));
    				return;
    			}
    			/*if(lockuser.getOpentype() == 0) {
    				if(authlist.toString().indexOf(",") >= 0) {
    					resjson.put("status", "2");
	    				resjson.put("desc", "开锁模式为单人,无法授权两人!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
    				}
    			}else {
    				if(authlist.toString().indexOf(",") < 0) {
    					resjson.put("status", "2");
	    				resjson.put("desc", "开锁模式为双人,请选择两人授权!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
    				}
    			}*/
    			lockuser.setActive(1);
    			lockuser.setOperators(authlist.toString());
    			lockuser.setOper_reals(sb.toString());
    			lockuser.setMissionid(mission.getId());
    			if(lockDao.updatelockuserActive(lockuser) == 0) {
    				resjson.put("status", "2");
    				resjson.put("desc", "更新授权信息失败!");
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    				deferredResult.setResult(mapper.writeValueAsString(resjson));
    				return;
    			}
    			//添加任务详情列表
				detail = new LockMissionDetailEntity();
				detail.setId(UUID.randomUUID().toString().replace("-", ""));
				detail.setStime(mission.getStime());
				detail.setEtime(mission.getEtime());
				detail.setAuthuser(authlist.toString());
				detail.setAuth_reals(sb.toString());
				detail.setLocksn(lockuser.getLocksn());
				detail.setMissionid(mission.getId());
				detail.setActive(1);
				if(missionDao.insertLockMissionDetail(detail) == 0) {
					resjson.put("status", "2");
    				resjson.put("desc", "添加锁具["+ lockuser.getLocksn() + "]任务信息失败!");
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    				deferredResult.setResult(mapper.writeValueAsString(resjson));
    				return;
				}
    		}else {
    			resjson.put("status", "2");
				resjson.put("desc", "找不到锁具[" + jnode.get("locksn").asText() + "]使用人信息!");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				deferredResult.setResult(mapper.writeValueAsString(resjson));
				return;
    		}
    	}
		
		if(missionDao.savemission(mission) == 0) {
			resjson.put("status", "2");
			resjson.put("desc", "创建任务失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		resjson.put("status", "1");
		resjson.put("desc", "创建成功!");
		ulog.setDescriptor("创建调拨任务");			
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
    
    public void _allotmissionedit(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
		String missionid = "";
		String descriptor = "";
		String stime = "";
		String etime = "";
		String ckname = "";
		int keyvalid = 0;
		JsonNode authuser = null;
		JsonNode childrenNode = null;
		LockMissionDetailEntity detail = null;
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			missionid =rootNode.get("missionid").asText();
			stime =rootNode.get("stime").asText();
			etime =rootNode.get("etime").asText();
			descriptor =rootNode.get("descriptor").asText();
			ckname =rootNode.get("ckname").asText();
			keyvalid =rootNode.get("keyvalid").asInt();
			childrenNode = rootNode.path("locks"); 
			authuser = rootNode.path("authuser"); 
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date start = null;
		Date end = null;
		
    	try {
    		start = dateFormat.parse(stime);
    		end = dateFormat.parse(etime);
    		if(end.before(start)) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于生效时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    		if(end.before(new Date())) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于当前时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    	}catch(Exception e) {
    		resjson.put("status", "2");
			resjson.put("desc", "任务时间设置异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	
    	Date date = new Date();
    	MissionEntity mission = missionDao.findMissionById(missionid);
    	if(mission == null) {
    		resjson.put("status", "2");
			resjson.put("desc", "找不到指定任务!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	};
    	StringBuilder authlist = new StringBuilder();
    	StringBuilder sb = new StringBuilder();
		Iterator<JsonNode> authit = authuser.iterator();
		int i = 0;
		while(authit.hasNext()){
    		JsonNode jnode = authit.next();
    		if(i == 0) {
    			authlist.append(jnode.get("username").asText());
    			sb.append(jnode.get("oper_reals").asText());
    		}else {
    			authlist.append("," + jnode.get("username").asText());
    			sb.append("," + jnode.get("oper_reals").asText());
    		}
    		i++;
		}
    	mission.setStime(start);
    	mission.setEtime(end);
    	mission.setDescriptor(descriptor);
    	mission.setCkname(ckname);
    	mission.setStopreason("");
    	mission.setAuthuser(authlist.toString());
    	mission.setAuth_reals(sb.toString());
    	mission.setActive(0);
    	mission.setKeyvalid(keyvalid);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/调拨任务/编辑任务");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_allotmissionedit");
		ulog.setOrgid(sentity.getOrg_id());
		
		//清空任务id下的授权信息
		if(lockDao.ResetLockUserInfoByMission(mission.getId()) == 0) {
			resjson.put("status", "2");
			resjson.put("desc", "重置任务授权信息失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		//删除原任务id对应的详情列表
		if(missionDao.deleteLockMissionDetail(mission.getId()) == -1) {
			resjson.put("status", "2");
			resjson.put("desc", "重置任务列表信息失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		//调拨任务
		Iterator<JsonNode> it = childrenNode.iterator();
		LockUserEntity lockuser = null;
    	while(it.hasNext()){
    		JsonNode jnode = it.next();
    		lockuser = lockDao.findLockUserByLock(jnode.get("locksn").asText());
    		if(lockuser != null) {
    			mission.setLocksn(lockuser.getLocksn());
    			if(lockuser.getActive() == 1 && !lockuser.getMissionid().equals("") && !lockuser.getMissionid().equalsIgnoreCase(mission.getId()) ) {
    				mission = missionDao.findMissionById(lockuser.getMissionid());
    				resjson.put("status", "2");
    				resjson.put("desc", "锁具[" + lockuser.getLocksn() + "]已在任务时间段[" + mission.getStime() + "-" + mission.getEtime() + "]授权!");
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    				deferredResult.setResult(mapper.writeValueAsString(resjson));
    				return;
    			}
    			/*if(lockuser.getOpentype() == 0) {
    				if(authlist.toString().indexOf(",") >= 0) {
    					resjson.put("status", "2");
	    				resjson.put("desc", "开锁模式为单人,无法授权两人!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
    				}
    			}else {
    				if(authlist.toString().indexOf(",") < 0) {
    					resjson.put("status", "2");
	    				resjson.put("desc", "开锁模式为双人,请选择两人授权!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
    				}
    			}*/
    			lockuser.setActive(1);
    			lockuser.setOperators(authlist.toString());
    			lockuser.setOper_reals(sb.toString());
    			lockuser.setMissionid(mission.getId());
    			if(lockDao.updatelockuserActive(lockuser) == 0) {
    				resjson.put("status", "2");
    				resjson.put("desc", "更新授权信息失败!");
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    				deferredResult.setResult(mapper.writeValueAsString(resjson));
    				return;
    			}
    			//添加任务详情列表
				detail = new LockMissionDetailEntity();
				detail.setId(UUID.randomUUID().toString().replace("-", ""));
				detail.setStime(mission.getStime());
				detail.setEtime(mission.getEtime());
				detail.setAuthuser(authlist.toString());
				detail.setAuth_reals(sb.toString());
				detail.setLocksn(lockuser.getLocksn());
				detail.setMissionid(mission.getId());
				detail.setActive(1);
				if(missionDao.insertLockMissionDetail(detail) == 0) {
					resjson.put("status", "2");
    				resjson.put("desc", "添加锁具["+ lockuser.getLocksn() + "]任务信息失败!");
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    				deferredResult.setResult(mapper.writeValueAsString(resjson));
    				return;
				}
    		}else {
    			resjson.put("status", "2");
				resjson.put("desc", "找不到锁具[" + jnode.get("locksn").asText() + "]使用人信息!");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				deferredResult.setResult(mapper.writeValueAsString(resjson));
				return;
    		}
    	}
		if(missionDao.updatemission(mission) == 0) {
			resjson.put("status", "2");
			resjson.put("desc", "编辑任务失败!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		resjson.put("status", "1");
		resjson.put("desc", "更新成功!");
		ulog.setDescriptor("更新调拨任务");		
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
    
    public void _allotmissionstop(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
		String missionid = "";
		String stopreason = "";
		String ckname = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			missionid =rootNode.get("missionid").asText();
			stopreason =rootNode.get("descriptor").asText();
			ckname =rootNode.get("ckname").asText();
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		
    	Date date = new Date();
    	if(missionDao.stopmission(missionid,stopreason) == -1) {
    		resjson.put("status", "2");
			resjson.put("desc", "更新任务异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	//更新锁具授权信息
    	MissionEntity mission = missionDao.findMissionById(missionid);
    	if(mission == null) {
    		resjson.put("status", "2");
			resjson.put("desc", "找不到指定任务!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	};
    	if(lockDao.ResetLockUserInfoByMission(missionid) == -1) {
			resjson.put("status", "2");
			resjson.put("desc", "更新任务授权信息失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
    	if(missionDao.updateLockMissionDetail_reasonByid(missionid, stopreason) == -1) {
			log.error("手动终止任务时更新终止原因失败!");
		}
    	SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/调拨/终止任务");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_allotmissionstop");
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setDescriptor("终止调拨任务");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		resjson.put("status", "1");
		resjson.put("desc", "操作成功!");
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}   
    
    public void _multimissionadd(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
		String descriptor = "";
		String stime = "";
		String etime = "";
		int mtype = 0;
		String ckname = "";
		String orgid = "";
		JsonNode authuser = null;
		JsonNode childrenNode = null;
		LockMissionDetailEntity detail = null;
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			stime =rootNode.get("stime").asText();
			etime =rootNode.get("etime").asText();
			descriptor =rootNode.get("descriptor").asText();
			mtype =rootNode.get("mtype").asInt();
			ckname =rootNode.get("ckname").asText();
			orgid =rootNode.get("orgid").asText();
			childrenNode = rootNode.path("locks"); 
			authuser = rootNode.path("authuser"); 
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date start = null;
		Date end = null;
		
    	try {
    		start = dateFormat.parse(stime);
    		end = dateFormat.parse(etime);
    		if(end.before(start)) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于生效时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    		if(end.before(new Date())) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于当前时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    	}catch(Exception e) {
    		resjson.put("status", "2");
			resjson.put("desc", "任务时间设置异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	
    	Date date = new Date();
    	MissionEntity mission = new MissionEntity();
    	mission.setId(UUID.randomUUID().toString().replace("-", ""));
    	mission.setCreatename(sentity.getUsername());
    	mission.setCreatetime(date);
    	StringBuilder authlist = new StringBuilder();
    	StringBuilder sb = new StringBuilder();
		Iterator<JsonNode> authit = authuser.iterator();
		int i = 0;
		while(authit.hasNext()){
    		JsonNode jnode = authit.next();
    		if(i == 0) {
    			authlist.append(jnode.get("username").asText());
    			sb.append(jnode.get("oper_reals").asText());
    		}else {
    			authlist.append("," + jnode.get("username").asText());
    			sb.append("," + jnode.get("oper_reals").asText());
    		}
    		i++;
		}
		mission.setAuthuser(authlist.toString());
    	mission.setAuth_reals(sb.toString());
    	mission.setStime(start);
    	mission.setEtime(end);
    	mission.setDescriptor(descriptor);
    	mission.setOrgid(orgid);
    	mission.setMtype(mtype);
    	mission.setCkname(ckname);
    	mission.setOpentype(1);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/任务管理/创建任务");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_missionadd");
		ulog.setOrgid(sentity.getOrg_id());
		
		//添加锁具授权信息
		if(mtype == 3) {
			//批量任务
			Iterator<JsonNode> it = authuser.iterator();
			String username = "";
			
			List<LockUserEntity> lockuserlist = null;
    		while(it.hasNext()){
	    		JsonNode jnode = it.next();
	    		username = jnode.get("username").asText();
	    		lockuserlist = lockDao.findDoubleUserLocksByUser(username);
	    		for(LockUserEntity lockuser : lockuserlist) {
	    			if(lockuser.getLocktype() == 3) {
	    				//调拨锁，这里不做处理
	    				continue;
	    			}
	    			//判断是否是同一任务授权
	    			if(!lockuser.getMissionid().equals(mission.getId()) && !lockuser.getMissionid().equals("")) {
	    				if(lockuser.getActive() == 1) {
	    					mission = missionDao.findMissionById(lockuser.getMissionid());
		    				resjson.put("status", "2");
		    				resjson.put("desc", "锁具["+ lockuser.getLocksn() + "]已在任务时间段[" + mission.getStime() + "-" + mission.getEtime() + "]授权!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;	
	    				}else {
	    					lockuser.setActive(1);
	    					lockuser.setMissionid(mission.getId());
	    					if(lockDao.updatelockuserActive(lockuser) == 0) {
	    						resjson.put("status", "2");
			    				resjson.put("desc", "更新锁具["+ lockuser.getLocksn() + "]授权信息失败!");
			    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			    				deferredResult.setResult(mapper.writeValueAsString(resjson));
			    				return;
	    					}
	    				}
	    			}else {
	    				//该锁被其它使用人激活
	    				if(lockuser.getActive() == 1) {
	    					continue;
	    				}else {
	    					lockuser.setActive(1);
	    					lockuser.setMissionid(mission.getId());
	    					if(lockDao.updatelockuserActive(lockuser) == 0) {
	    						resjson.put("status", "2");
			    				resjson.put("desc", "更新锁具["+ lockuser.getLocksn() + "]授权信息失败!");
			    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			    				deferredResult.setResult(mapper.writeValueAsString(resjson));
			    				return;
	    					}
	    					
	    				}
	    			}
	    			//添加任务详情列表
					detail = new LockMissionDetailEntity();
					detail.setId(UUID.randomUUID().toString().replace("-", ""));
					detail.setStime(mission.getStime());
					detail.setEtime(mission.getEtime());
					detail.setAuthuser(lockuser.getOperators());
					detail.setAuth_reals(lockuser.getOper_reals());
					detail.setLocksn(lockuser.getLocksn());
					detail.setMissionid(mission.getId());
					if(missionDao.insertLockMissionDetail(detail) == 0) {
						resjson.put("status", "2");
	    				resjson.put("desc", "添加锁具["+ lockuser.getLocksn() + "]任务信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
					}
	    		}   		
	    		
    		}
		}else if(mtype == 2) {
			//应急任务
			Iterator<JsonNode> it = childrenNode.iterator();
			LockUserEntity lockuser = null;
	    	while(it.hasNext()){
	    		JsonNode jnode = it.next();
	    		lockuser = lockDao.findLockUserByLock(jnode.get("locksn").asText());
	    		if(lockuser != null) {
	    			mission.setLocksn(lockuser.getLocksn());
	    			if(lockuser.getActive() == 1 && !lockuser.getMissionid().equals("") && !lockuser.getMissionid().equalsIgnoreCase(mission.getId()) ) {
	    				mission = missionDao.findMissionById(lockuser.getMissionid());
	    				resjson.put("status", "2");
	    				resjson.put("desc", "锁具[" + lockuser.getLocksn() + "]已在任务时间段[" + mission.getStime() + "-" + mission.getEtime() + "]授权!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
	    			}
	    			if(lockuser.getOpentype() == 0) {
	    				if(authlist.toString().indexOf(",") >= 0) {
	    					resjson.put("status", "2");
		    				resjson.put("desc", "开锁模式为单人,无法授权两人!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;
	    				}
	    			}else {
	    				if(authlist.toString().indexOf(",") < 0) {
	    					resjson.put("status", "2");
		    				resjson.put("desc", "开锁模式为双人,请选择多人授权!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;
	    				}
	    			}
	    			lockuser.setActive(1);
	    			lockuser.setMissionid(mission.getId());
	    			if(lockDao.updatelockuserActive(lockuser) == 0) {
	    				resjson.put("status", "2");
	    				resjson.put("desc", "更新授权信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
	    			}
	    			//添加任务详情列表
					detail = new LockMissionDetailEntity();
					detail.setId(UUID.randomUUID().toString().replace("-", ""));
					detail.setStime(mission.getStime());
					detail.setEtime(mission.getEtime());
					detail.setAuthuser(authlist.toString());
					detail.setAuth_reals(sb.toString());
					detail.setLocksn(lockuser.getLocksn());
					detail.setMissionid(mission.getId());
					if(missionDao.insertLockMissionDetail(detail) == 0) {
						resjson.put("status", "2");
	    				resjson.put("desc", "添加锁具["+ lockuser.getLocksn() + "]任务信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
					}
	    		}else {
	    			resjson.put("status", "2");
    				resjson.put("desc", "找不到锁具[" + jnode.get("locksn").asText() + "]使用人信息!");
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    				deferredResult.setResult(mapper.writeValueAsString(resjson));
    				return;
	    		}
	    	}
		}else {
			resjson.put("status", "2");
			resjson.put("desc", "未知任务类型失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		
		if(missionDao.savemission(mission) == 0) {
			resjson.put("status", "2");
			resjson.put("desc", "创建任务失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		resjson.put("status", "1");
		resjson.put("desc", "创建成功!");
		if(mtype == 0) {
			ulog.setDescriptor("创建日常任务");
		}else {
			ulog.setDescriptor("创建应急任务");
		}			
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
    
    public void _multimissionedit(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
		String missionid = "";
		String descriptor = "";
		String stime = "";
		String etime = "";
		String ckname = "";
		int mtype = 0;
		JsonNode authuser = null;
		JsonNode childrenNode = null;
		LockMissionDetailEntity detail = null;
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			missionid =rootNode.get("missionid").asText();
			stime =rootNode.get("stime").asText();
			etime =rootNode.get("etime").asText();
			descriptor =rootNode.get("descriptor").asText();
			ckname =rootNode.get("ckname").asText();
			mtype =rootNode.get("mtype").asInt();
			childrenNode = rootNode.path("locks"); 
			authuser = rootNode.path("authuser"); 
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date start = null;
		Date end = null;
		
    	try {
    		start = dateFormat.parse(stime);
    		end = dateFormat.parse(etime);
    		if(end.before(start)) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于生效时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    		if(end.before(new Date())) {
    			resjson.put("status", "2");
    			resjson.put("desc", "终止时间应不早于当前时间!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    	}catch(Exception e) {
    		resjson.put("status", "2");
			resjson.put("desc", "任务时间设置异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	
    	Date date = new Date();
    	MissionEntity mission = missionDao.findMissionById(missionid);
    	if(mission == null) {
    		resjson.put("status", "2");
			resjson.put("desc", "找不到指定任务!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	};
    	StringBuilder authlist = new StringBuilder();
    	StringBuilder sb = new StringBuilder();
		Iterator<JsonNode> authit = authuser.iterator();
		int i = 0;
		while(authit.hasNext()){
    		JsonNode jnode = authit.next();
    		if(i == 0) {
    			authlist.append(jnode.get("username").asText());
    			sb.append(jnode.get("oper_reals").asText());
    		}else {
    			authlist.append("," + jnode.get("username").asText());
    			sb.append("," + jnode.get("oper_reals").asText());
    		}
    		i++;
		}
    	mission.setStime(start);
    	mission.setEtime(end);
    	mission.setDescriptor(descriptor);
    	mission.setCkname(ckname);
    	mission.setStopreason("");
    	mission.setAuthuser(authlist.toString());
    	mission.setAuth_reals(sb.toString());
    	mission.setActive(0);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/任务管理/创建任务");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_missionedit");
		ulog.setOrgid(sentity.getOrg_id());
		
		//清空任务id下的授权信息
		if(lockDao.ResetLockUserInfoByMission(mission.getId()) == 0) {
			resjson.put("status", "2");
			resjson.put("desc", "重置任务授权信息失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		//删除原任务id对应的详情列表
		if(missionDao.deleteLockMissionDetail(mission.getId()) == -1) {
			resjson.put("status", "2");
			resjson.put("desc", "重置任务列表信息失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		//修改锁具授权信息
		if(mtype == 3) {
			//批量任务
			Iterator<JsonNode> it = authuser.iterator();
			String username = "";
			
			List<LockUserEntity> lockuserlist = null;
    		while(it.hasNext()){
	    		JsonNode jnode = it.next();
	    		username = jnode.get("username").asText();
	    		lockuserlist = lockDao.findDoubleUserLocksByUser(username);
	    		for(LockUserEntity lockuser : lockuserlist) {
	    			if(lockuser.getLocktype() == 3) {
	    				//调拨锁，这里不做处理
	    				continue;
	    			}
	    			//判断是否是同一任务授权
	    			if(!lockuser.getMissionid().equals(mission.getId()) && !lockuser.getMissionid().equals("")) {
	    				if(lockuser.getActive() == 1) {
	    					mission = missionDao.findMissionById(lockuser.getMissionid());
		    				resjson.put("status", "2");
		    				resjson.put("desc", "锁具["+ lockuser.getLocksn() + "]已在任务时间段[" + mission.getStime() + "-" + mission.getEtime() + "]授权!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;	
	    				}else {
	    					lockuser.setActive(1);
	    					lockuser.setMissionid(mission.getId());
	    					if(lockDao.updatelockuserActive(lockuser) == 0) {
	    						resjson.put("status", "2");
			    				resjson.put("desc", "更新锁具["+ lockuser.getLocksn() + "]授权信息失败!");
			    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			    				deferredResult.setResult(mapper.writeValueAsString(resjson));
			    				return;
	    					}
	    				}
	    			}else {
	    				//该锁被其它使用人激活
	    				if(lockuser.getActive() == 1) {
	    					continue;
	    				}else {
	    					lockuser.setActive(1);
	    					lockuser.setMissionid(mission.getId());
	    					if(lockDao.updatelockuserActive(lockuser) == 0) {
	    						resjson.put("status", "2");
			    				resjson.put("desc", "更新锁具["+ lockuser.getLocksn() + "]授权信息失败!");
			    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			    				deferredResult.setResult(mapper.writeValueAsString(resjson));
			    				return;
	    					}
	    					
	    				}
	    			}
	    			//添加任务详情列表
					detail = new LockMissionDetailEntity();
					detail.setId(UUID.randomUUID().toString().replace("-", ""));
					detail.setStime(mission.getStime());
					detail.setEtime(mission.getEtime());
					detail.setAuthuser(lockuser.getOperators());
					detail.setAuth_reals(lockuser.getOper_reals());
					detail.setLocksn(lockuser.getLocksn());
					detail.setMissionid(mission.getId());
					if(missionDao.insertLockMissionDetail(detail) == 0) {
						resjson.put("status", "2");
	    				resjson.put("desc", "添加锁具["+ lockuser.getLocksn() + "]任务信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
					}
	    		}   		
	    		
    		}
		}else if(mtype == 2) {
			//应急任务
			Iterator<JsonNode> it = childrenNode.iterator();
			LockUserEntity lockuser = null;
	    	while(it.hasNext()){
	    		JsonNode jnode = it.next();
	    		lockuser = lockDao.findLockUserByLock(jnode.get("locksn").asText());
	    		if(lockuser != null) {
	    			mission.setLocksn(lockuser.getLocksn());
	    			if(lockuser.getActive() == 1 && !lockuser.getMissionid().equals("") && !lockuser.getMissionid().equalsIgnoreCase(mission.getId()) ) {
	    				mission = missionDao.findMissionById(lockuser.getMissionid());
	    				resjson.put("status", "2");
	    				resjson.put("desc", "锁具[" + lockuser.getLocksn() + "]已在任务时间段[" + mission.getStime() + "-" + mission.getEtime() + "]授权!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
	    			}
	    			if(lockuser.getOpentype() == 0) {
	    				if(authlist.toString().indexOf(",") >= 0) {
	    					resjson.put("status", "2");
		    				resjson.put("desc", "开锁模式为单人,无法授权两人!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;
	    				}
	    			}else {
	    				if(authlist.toString().indexOf(",") < 0) {
	    					resjson.put("status", "2");
		    				resjson.put("desc", "开锁模式为双人,请选择多人授权!");
		    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		    				deferredResult.setResult(mapper.writeValueAsString(resjson));
		    				return;
	    				}
	    			}
	    			lockuser.setActive(1);
	    			lockuser.setMissionid(mission.getId());
	    			if(lockDao.updatelockuserActive(lockuser) == 0) {
	    				resjson.put("status", "2");
	    				resjson.put("desc", "更新授权信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
	    			}
	    			//添加任务详情列表
					detail = new LockMissionDetailEntity();
					detail.setId(UUID.randomUUID().toString().replace("-", ""));
					detail.setStime(mission.getStime());
					detail.setEtime(mission.getEtime());
					detail.setAuthuser(authlist.toString());
					detail.setAuth_reals(sb.toString());
					detail.setLocksn(lockuser.getLocksn());
					detail.setMissionid(mission.getId());
					if(missionDao.insertLockMissionDetail(detail) == 0) {
						resjson.put("status", "2");
	    				resjson.put("desc", "添加锁具["+ lockuser.getLocksn() + "]任务信息失败!");
	    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    				deferredResult.setResult(mapper.writeValueAsString(resjson));
	    				return;
					}
	    		}else {
	    			resjson.put("status", "2");
    				resjson.put("desc", "找不到锁具[" + jnode.get("locksn").asText() + "]使用人信息!");
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    				deferredResult.setResult(mapper.writeValueAsString(resjson));
    				return;
	    		}
	    	}
		}else {
			resjson.put("status", "2");
			resjson.put("desc", "未知任务类型失败!");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		if(missionDao.updatemission(mission) == 0) {
			resjson.put("status", "2");
			resjson.put("desc", "编辑任务失败!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		resjson.put("status", "1");
		resjson.put("desc", "更新成功!");
		if(mtype == 0) {
			ulog.setDescriptor("更新日常任务");
		}else {
			ulog.setDescriptor("更新应急任务");
		}			
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
    
    public void getMissionList_template(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
		String owner = "";
		String missionid = "";
		String locksn = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);		
			owner =rootNode.get("owner").asText();
			missionid =rootNode.get("missionid").asText();
			locksn =rootNode.get("locksn").asText();
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
    	List<MissionDetailEntity> mlist = null;
    	int precount = 0;
    	mlist =missionDao.findMissionDetailByQuery(owner,missionid,locksn);

		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	ArrayNode rootnode = mapper.createArrayNode();
    	if(mlist != null && mlist.size() > 0){
    		precount = mlist.size();
    		ObjectNode tjson = null;
    		for(MissionDetailEntity mission : mlist){
    			tjson = mapper.createObjectNode();
    			tjson.put("id", mission.getId());
    			tjson.put("locksn", mission.getLocksn());
    			tjson.put("stime", sdf.format(mission.getStime()));
    			tjson.put("etime", sdf.format(mission.getEtime()));
    			tjson.put("active", mission.getActive());
    			tjson.put("operators", mission.getOperators());
    			tjson.put("oper_reals", mission.getOper_reals());
    			tjson.put("stopreason", mission.getStopreason());
    			rootnode.add(tjson);
        	}
    		
    	}
    	
    	resjson.put("status", "1");
    	resjson.put("totalCount", precount);
    	resjson.put("datalist", rootnode);
    	deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}
    
    public void _stopmission_multi(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();  	
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
		String missionid = "";
		JsonNode locklist = null;
		boolean isAll = false;
		String ckname = "";
		String stopreason = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			missionid =rootNode.get("missionid").asText();
			isAll =rootNode.get("isAll").asBoolean();
			stopreason =rootNode.get("stopreason").asText();
			ckname =rootNode.get("ckname").asText();
			locklist = rootNode.path("locklist");
		} catch (Exception e1) {
			resjson.put("status", "2");
			resjson.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		
    	Date date = new Date();
    	if(isAll) {
    		if(missionDao.stopmission(missionid,stopreason) == -1) {
        		resjson.put("status", "2");
    			resjson.put("desc", "更新任务异常!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
        	}
    		if(lockDao.ResetLockUserInfoByMission(missionid) == -1) {
    			resjson.put("status", "2");
    			resjson.put("desc", "更新任务授权信息失败!");
    			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    		if(missionDao.updateLockMissionDetail_reasonByid(missionid, stopreason) == -1) {
    			log.error("手动终止任务时更新终止原因失败!");
    		}
    	}else {
    		//更新锁具授权信息
    		Iterator<JsonNode> it = locklist.iterator();
    		String locksn = "";
    		while(it.hasNext()){
        		JsonNode jnode = it.next();
        		locksn = jnode.get("locksn").asText();
        		if(lockDao.setActiveByLocksn(0, locksn) == -1) {
        			resjson.put("status", "2");
        			resjson.put("desc", "更新锁具[" + locksn +  "]授权信息失败!");
        			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        			deferredResult.setResult(mapper.writeValueAsString(resjson));
        			return;
        		}
        		if(missionDao.updateLockMissionDetail_reason(locksn,missionid, stopreason) == -1) {
        			//发生的错误不影响业务执行,不中断
        			log.error("手动终止任务时更新终止原因失败!");
        		}
    		}
    	}
    	
    	SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/任务管理/终止任务");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("_stopmission_multi");
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setDescriptor("终止日常任务");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		resjson.put("status", "1");
		resjson.put("desc", "操作成功!");
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
	}   
}
